package com.huiztech.kaoqinji;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.huiztech.common.http.HuizBaseJsonResponseHandler.Callback;
import com.huiztech.kaoqinji.model.SignOn;
import com.huiztech.kaoqinji.model.UserInfoDetail;
import com.huiztech.kaoqinji.view.SlideBar;
import com.huiztech.kaoqinji.view.SlideBar.OnTriggerListener;
import com.huiztech.util.GetScreen;
import com.huiztech.util.SlidingButton;
public class MainActivity extends BaseActivity implements OnClickListener ,OnTriggerListener{

    // 定位相关
    public LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    // UI 相关
    private AlertDialog dialog;
    boolean isRequest = true; // 是否手动触发请求定位
   // private SlidingButton kaoqinBtn;
    private LinearLayout footprintBtn;
    private LinearLayout visitBtn;
    private TextView slidingText;
    private TextView nameText, positionText, phoneText;
    private ImageView userImage;
    private long exitTime = 0;

    private SlideBar slideToUnLock;
    public static int MaxDistance;
    private LayoutParams params;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MaxDistance=(int) GetScreen.GetScreenWidth(MainActivity.this);
        findView();
        initUI();

        footprintBtn.setOnClickListener(this);
        visitBtn.setOnClickListener(this);

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        setLocationOption();
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (kaoqinBtn.handleActivityEvent(event)) {
//            // TODO: 这里如果不用中文判断,需要将状态标记存入到本地,文件读写会影响速度
//            if (slidingText.getText().toString().equals(getResources().getString(R.string.SlideSignOn))) {
//                showDialog();
//            } else {
//                showQTDialog();
//            }
//        }
//        return super.onTouchEvent(event);
//    }

    private void initUI() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int windowsWidth = wm.getDefaultDisplay().getWidth();
        int windowsHeight = wm.getDefaultDisplay().getHeight();
        int width = (int) (windowsWidth * 0.50); // 宽度
        int height = width;// 高度

        params = (LayoutParams) userImage.getLayoutParams();
        params.width = width;
        params.height = height;
        userImage.setLayoutParams(params);
//
        if (controller.getInfoByLocal(AppConst.SP_ATTENDANCE_KEY, null) == null) {
            slidingText.setText(getResources().getString(R.string.SlideSignOn));
            slideToUnLock.setBackgroundResource(R.drawable.slide_bg);
        } else {
            slidingText.setText(getResources().getString(R.string.SlideSignOut));
            slideToUnLock.setBackgroundResource(R.drawable.slide_bg_red);
            //slideToUnLock.setBackgroundResource(R.drawable.slide_bg_red);
        }

        UserInfoDetail userInfoDetail = (UserInfoDetail) model.get("user");
        nameText.setText(userInfoDetail.getName());
        phoneText.setText(userInfoDetail.getPhone());
        positionText.setText(userInfoDetail.getPosition());

        if (userInfoDetail.getImage().equals("")) {
            userImage.setBackgroundResource(R.drawable.moren);
        } else {
            imageLoader.displayImage(AppConst.KAOQIN_UPLOAD_URL + userInfoDetail.getImage(), userImage, options);
        }
    }

    /**
     * 定位监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            int type = location.getLocType();
            // Log.e("onReceiveLocaiont--", "type =" + type);
            // Log.e("BDLocation.TypeCacheLocation",
            // BDLocation.TypeCacheLocation + "");//65
            // Log.e("BDLocation.TypeCriteriaException",
            // BDLocation.TypeCriteriaException + "");//62
            // Log.e("BDLocation.TypeGpsLocation", BDLocation.TypeGpsLocation +
            // "");//61
            // Log.e("BDLocation.TypeNetWorkException",
            // BDLocation.TypeNetWorkException + "");//63
            // Log.e("BDLocation.TypeNetWorkLocation",
            // BDLocation.TypeNetWorkLocation + "");//161
            // Log.e("BDLocation.TypeNone", BDLocation.TypeNone + "");//0
            // Log.e("BDLocation.TypeOffLineLocation",
            // BDLocation.TypeOffLineLocation + "");//66
            // Log.e("BDLocation.TypeOffLineLocationFail",
            // BDLocation.TypeOffLineLocationFail + "");//67
            // Log.e("BDLocation.TypeOffLineLocationNetworkFail",
            // BDLocation.TypeOffLineLocationNetworkFail + "");//68
            // Log.e("BDLocation.TypeServerError", BDLocation.TypeServerError +
            // "");//167

            if (type == BDLocation.TypeCriteriaException || type == BDLocation.TypeNetWorkException
                    || type == BDLocation.TypeOffLineLocation || type == BDLocation.TypeOffLineLocationFail
                    || ((type > BDLocation.TypeNetWorkLocation) && (type < BDLocation.TypeServerError))) {
                view.showMessage("无法定位到当前位置!");
            } else {
                if (slidingText.getText().toString().equals(getResources().getString(R.string.SlideSignOn))) {
                    controller.doSignOn(location.getLatitude(), location.getLongitude(), new Callback<SignOn>() {

                        @Override
                        public void execute(SignOn obj) {
                            slidingText.setText(getResources().getString(R.string.SlideSignOut));
                            slideToUnLock.setBackgroundResource(R.drawable.slide_bg_red);
                         //   slidingText.setBackgroundResource(R.drawable.slide_bg_red);
                            slideToUnLock.resetControls();
                        }
                    });
                } else {
                    controller.doSignOut(location.getLatitude(), location.getLongitude(), new Callback<SignOn>() {

                        @Override
                        public void execute(SignOn obj) {
                            slidingText.setText(getResources().getString(R.string.SlideSignOn));
                            slideToUnLock.setBackgroundResource(R.drawable.slide_bg);
                         //   slidingText.setBackgroundResource(R.drawable.slide_bg);
                            slideToUnLock.resetControls();
                        }
                    });
                }

            }

        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }

    }

    /**
     * 手动触发一次定位请求
     */
    public void requestLocClick() {
        mLocClient.start();
        mLocClient.requestLocation();
    }

    // 设置相关参数
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setPriority(LocationClientOption.GpsFirst);
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setAddrType("all");
        option.setServiceName("com.baidu.location.service_v2.9");
        mLocClient.setLocOption(option);
    }

    private void findView() {
        // kaoqinBtn = (SlidingButton) findViewById(R.id.main_sliding_btn);
        slideToUnLock = (SlideBar) findViewById(R.id.slideBar);
        visitBtn = (LinearLayout) findViewById(R.id.main_visit_layout);
        footprintBtn = (LinearLayout) findViewById(R.id.main_footprint_layout);
        nameText = (TextView) findViewById(R.id.main_user_name);
        positionText = (TextView) findViewById(R.id.main_user_position);
        phoneText = (TextView) findViewById(R.id.main_user_phone);
        userImage = (ImageView) findViewById(R.id.main_user_image);
        slidingText = (TextView) findViewById(R.id.main_sliding_text);
        slideToUnLock.setOnTriggerListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.main_footprint_layout:
            startActivity(new Intent(MainActivity.this, FootprintActivity.class));
            break;
        case R.id.main_visit_layout:
            startActivity(new Intent(MainActivity.this, VisitActivity.class));
            break;
        default:
            break;
        }
    }

    // 后退事件
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(event.getKeyCode(), event);
    }

    private void showDialog() {
        // view.showDialog(R.layout.qiandao_dialog,
        // R.id.qiandao_dialog_cancel_btn, R.id.qiandao_dialog_submit_btn,
        // new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // if (sp.getString(AppConst.SP_VISIT_KEY, null) == null) {
        // requestLocClick();
        // view.dialog.dismiss();
        // } else {
        // view.showMessage("请先结束上次拜访!");
        // }
        // }
        // });
        dialog = new AlertDialog.Builder(MainActivity.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
        dialog.getWindow().setContentView(R.layout.qiandao_dialog);
        dialog.getWindow().findViewById(R.id.qiandao_dialog_cancel_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                slideToUnLock.resetControls();
            }
        });

        dialog.getWindow().findViewById(R.id.qiandao_dialog_submit_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                requestLocClick();
                dialog.dismiss();

            }
        });
    }

    private void showQTDialog() {
        // view.showDialog(R.layout.qiantui_dialog, R.id.qiantui_cancel_btn,
        // R.id.qiantui_submit_btn,
        // new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // if (sp.getString(AppConst.SP_VISIT_KEY, null) == null) {
        // requestLocClick();
        // view.dialog.dismiss();
        // } else {
        // view.showMessage("请先结束上次拜访!");
        // }
        // }
        // });
        dialog = new AlertDialog.Builder(MainActivity.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
        dialog.getWindow().setContentView(R.layout.qiantui_dialog);
        dialog.getWindow().findViewById(R.id.qiantui_cancel_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                slideToUnLock.resetControls();
            }
        });

        dialog.getWindow().findViewById(R.id.qiantui_submit_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (controller.sp.getInt(AppConst.SP_CUSTOMER_ID_KEY, -1) == -1) {
                    requestLocClick();
                    slideToUnLock.resetControls();
                } else {
                    view.showMessage("请先结束上次拜访!");
                }
            }
        });
    }

    @Override
    public void onTrigger() {
        if (slidingText.getText().toString().equals(getResources().getString(R.string.SlideSignOn))) {
            showDialog();
        } else {
            showQTDialog();
        }
    }

}
